package com.net.xpay.common.service.impl;

import com.net.xpay.common.domain.DailyTaskRecord;
import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.domain.partner.PartnerDailyStat;
import com.net.xpay.common.manager.UserManager;
import com.net.common.util.LocalDateUtil;
import com.net.xpay.common.manager.partner.PartnerDailyStatManager;
import com.net.xpay.common.manager.partner.PartnerManager;
import com.net.xpay.common.service.PartnerDailyStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class PartnerDilyStatServiceImpl implements PartnerDailyStatService {


    @Autowired
    private UserManager userManager;

    @Autowired
    private PartnerDailyStatManager partnerDailyStatManager;

    @Autowired
    private PartnerManager partnerManager;


    @Override
    public void statPartnerDaily(LocalDate day, DailyTaskRecord record) {
        List<Partner> partnerList = partnerManager.listAll();
        record.setTotalCount((long) partnerList.size());
        for (Partner partner : partnerList) {
            try {
                doPartnerDailyStat(partner.getId(), day);
                record.setSuccessCount(record.getSuccessCount() + 1L);
            } catch (Exception e) {
                record.setFailedCount(record.getFailedCount() + 1L);
                log.error("doPartnerDailyStat error|partnerId={}", partner.getId(), e);
            }
        }
    }


    @Override
    public void doPartnerDailyStat(Long partnerId, LocalDate day) {
        PartnerDailyStat dailyStat = new PartnerDailyStat();

        // 先去判断该用户当天统计记录是否存在
        dailyStat.setPartnerId(partnerId);
        dailyStat.setDay(day);
        dailyStat.setRegisterCount(0L);
        boolean exitRecord = hasStated(dailyStat);
        if (exitRecord) {
            log.warn("doPartnerDailyStat the record of partnerId={}|day={} is already exist", partnerId, day);
            return;
        }
        // 获取当天的起始时间和终止时间 终止时间保留在23:59:59.999999999
        LocalDateTime minEndTime = LocalDateUtil.getDayStart(day);
        LocalDateTime maxEndTime = LocalDateUtil.getDayEnd(day);
        //统计查询
        //user表统计
        long registerCount = userManager.countRegister(partnerId, minEndTime, maxEndTime);
        dailyStat.setRegisterCount(registerCount);
        partnerDailyStatManager.save(dailyStat);
    }

    private boolean hasStated(PartnerDailyStat partnerDailyStat) {
        LocalDate day = partnerDailyStat.getDay();
        // 尝试通过时间加id获取数据
        PartnerDailyStat partnerDailyStatRecord = partnerDailyStatManager.findByDayAndPartnerId(day, partnerDailyStat.getPartnerId());
        // 若果查到了数据，表示不需要在插入记录了
        return partnerDailyStatRecord != null;
    }


}
